// 基础库
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "esp_timer.h"
// ESPIDF官方组件库
#include "led_strip.h"
// 第三方拓展库
#include "OLED.h"
#include "ws2812.h"

// 全局变量存储当前RGB值
uint8_t current_red = 255;
uint8_t current_green = 0;
uint8_t current_blue = 0;

void OLED_display_task(void *pvParameters)
{
    ESP_LOGI("OLED_display_task", "Starting OLED display task");
    while (1)
    {
        vTaskDelay(pdMS_TO_TICKS(10));  // 降低刷新频率避免闪烁
        OLED_Clear();
        OLED_ShowString(28, 0, "ESPRESSIF", OLED_8X16);
        OLED_ShowString(36, 16, "ESP32S3", OLED_8X16);

        // 显示RGB值
        OLED_ShowString(0, 32, "R:", OLED_8X16);
        OLED_ShowNum(16, 32, current_red, 3, OLED_8X16);

        OLED_ShowString(0, 48, "G:", OLED_8X16);
        OLED_ShowNum(16, 48, current_green, 3, OLED_8X16);

        OLED_ShowString(64, 48, "B:", OLED_8X16);
        OLED_ShowNum(80, 48, current_blue, 3, OLED_8X16);

        OLED_Update();
    }
}
void ws2812_task(void *pvParameters)
{
    ESP_LOGI("ws2812_task", "Starting WS2812 task");
    uint8_t red = 255, green = 0, blue = 0;  // 初始颜色：红色
    uint8_t step = 0;  // 渐变步骤

    while (1)
    {
        vTaskDelay(pdMS_TO_TICKS(20));  // 调整延时以控制渐变速度

        // 三原色渐变循环：红 -> 绿 -> 蓝 -> 红
        switch (step) {
            case 0:  // 红色渐变到绿色
                if (green < 255) {
                    green += 5;
                } else if (red > 0) {
                    red -= 5;
                } else {
                    step = 1;  // 进入下一阶段
                }
                break;

            case 1:  // 绿色渐变到蓝色
                if (blue < 255) {
                    blue += 5;
                } else if (green > 0) {
                    green -= 5;
                } else {
                    step = 2;  // 进入下一阶段
                }
                break;

            case 2:  // 蓝色渐变到红色
                if (red < 255) {
                    red += 5;
                } else if (blue > 0) {
                    blue -= 5;
                } else {
                    step = 0;  // 回到第一阶段
                }
                break;
        }

        // 更新全局RGB值供OLED显示
        current_red = red;
        current_green = green;
        current_blue = blue;

        // 设置LED颜色并刷新
        led_strip_set_pixel(led_strip, 0, red, green, blue);
        led_strip_refresh(led_strip);
    }
}

void app_main()
{
    OLED_Init();
    ws2812_init();
    xTaskCreate(OLED_display_task, "OLED_display_task", 2048, NULL, 5, NULL);
    xTaskCreate(ws2812_task, "ws2812_task", 2048, NULL, 5, NULL);

    while (1)
    {
        vTaskDelay(pdMS_TO_TICKS(1000));
        ESP_LOGI("app_main", "Hello World");
    }
}
